<template>
  <view>
    <view :class="['container', pageOverfllow ? 'pagenoscroll' : '']">
      <view class="line"></view>
      <u-form style="padding: " labelPosition="left" :model="form" ref="form1" labelWidth="130">
        <u-form-item label="编号" prop="houseNo" borderBottom required>
          <u-input
            v-model="form.houseNo"
            border="none"
            placeholder="请输入编号"
            @blur="handleCheckHouseNo(form.houseNo)"
          ></u-input>
        </u-form-item>
        <u-form-item
          label="行业选择"
          prop="industrySel"
          borderBottom
          required
          @click="
            industryTypeShow = true;
            hideKeyboard();
          "
        >
          <u--input
            :key="i"
            :value="form.industrySel | showIndustryTypeVal"
            disabled
            border="none"
            placeholder="请选择"
            disabledColor="#fff"
          >
          </u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="户主姓名" prop="houseOwnerName" borderBottom required>
          <u-input v-model="form.houseOwnerName" border="none" placeholder="请输入户主姓名"></u-input>
        </u-form-item>
        <u-form-item label="门牌号" prop="houseNumber" borderBottom>
          <u-input v-model="form.houseNumber" border="none" placeholder="请输入门牌号"></u-input>
        </u-form-item>
        <u-form-item label="房屋层数" prop="floorNum" borderBottom required>
          <u-input v-model="form.floorNum" type="number" border="none" placeholder="请输入房屋层数"></u-input>
          <div slot="right">层</div>
        </u-form-item>
        <u-form-item label="常住人口数" prop="permanentPopulation" borderBottom required>
          <u-input v-model="form.permanentPopulation" border="none" placeholder="请输入人数" type=""></u-input>
          <div slot="right">人</div>
        </u-form-item>
        <u-form-item label="房屋地址" prop="position" borderBottom @click="selectAddress" required>
          <u-input v-model="form.position" border="none" placeholder="请选取地址" type=""></u-input>
          <image
            slot="right"
            style="width: 65rpx; height: 65rpx"
            src="http://123.156.228.151:3000/images/img/map.png"
            mode=""
          ></image>
        </u-form-item>
        <!-- 三水 -->
        <view class="title" style="margin-top: 20rpx">"三水"是否规范接入污水管网</view>
        <u-form-item label="厨房废水" prop="cffs" borderBottom required>
          <div slot="right">
            <u-radio-group v-model="form.cffs" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <u-form-item label="卫生间污水" prop="wsjws" borderBottom required>
          <div slot="right">
            <u-radio-group v-model="form.wsjws" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <u-form-item label="阳台洗衣污水" prop="ytxyws" borderBottom required>
          <div slot="right">
            <u-radio-group v-model="form.ytxyws" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <u-form-item label="化粪池（沼气池）数量" prop="zqcsl" borderBottom>
          <u-input v-model="form.zqcsl" type="number" border="none" placeholder="请填写"></u-input>
        </u-form-item>
        <u-form-item label="隔油池" prop="gyc" borderBottom>
          <div slot="right">
            <u-radio-group v-model="form.gyc" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <u-form-item label="毛发收集器" prop="mfsj" borderBottom>
          <div slot="right">
            <u-radio-group v-model="form.mfsj" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <u-form-item label="沉淀池" prop="cdc" borderBottom>
          <div slot="right">
            <u-radio-group v-model="form.cdc" placement="row">
              <u-radio :name="1" label="是" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
              <u-radio :name="0" label="否" :customStyle="{ marginLeft: '20rpx' }"></u-radio>
            </u-radio-group>
          </div>
        </u-form-item>
        <view v-for="(question, i) in form.quesList" :key="i">
          <u-form-item :label="'问题' + (i - -1)">
            <!-- <image
							style="width: 43.33rpx; height: 43.33rpx; margin: 0 0 0 auto"
							src="https://zjhcsj.com/images/img/trash.png"
							mode=""
							@click="deleteQuestion(i)"
						></image> -->

            <u-icon
              custom-style="width: 43.33rpx; height: 43.33rpx; margin: 0 0 0 auto"
              color="#ddd"
              size="30"
              name="trash"
              @click="deleteQuestion(i)"
            ></u-icon>
          </u-form-item>
          <view class="question-container">
            <u-form-item
              label="问题类型"
              borderBottom
              @click="
                problemTypeShow = true;
                quesIndex = i;
                hideKeyboard();
              "
              :key="i"
            >
              <u--input
                :key="i"
                :value="question.quesType | showQuesTypeVal(questionType)"
                disabled
                border="none"
                placeholder="请选择问题类型"
                disabledColor="#fff"
              >
              </u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item label="问题描述" borderBottom :key="i">
              <u-input v-model="question.quesDesc" border="none" placeholder="请输入问题描述"></u-input>
            </u-form-item>
            <view class="files-container">
              <view v-if="question.picDataList.length" class="pic-wrap">
                <view v-for="(pic, j) in question.picDataList" :key="j" class="pic-item">
                  <u-icon
                    custom-style="position: absolute; top: 4rpx;right: 4rpx;"
                    name="close-circle"
                    color="#ddd"
                    size="24"
                    @click="handleClearImg(i, j)"
                  ></u-icon>
                  <image class="pic-dom" mode="aspectFit" :src="pic.url" @click="handleViewPic(pic.url)"></image>
                </view>
              </view>
              <u-icon
                v-else
                custom-style="border:1px solid #ddd;padding: 20rpx;"
                name="plus"
                color="#ddd"
                size="80"
                @click="handleTuYa(i)"
              ></u-icon>
            </view>
          </view>
          <u-button type="primary" :plain="true" text="新增问题" @click="addQuestion"></u-button>
        </view>
      </u-form>
      <view class="page-btn-wrap">
        <view class="btn-item">
          <u-button type="primary" text="提交" customStyle="margin: auto 0" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-picker
      v-if="questionType.length"
      :show="problemTypeShow"
      keyName="label"
      :columns="[questionType]"
      @confirm="handleConfirmQues"
      @cancel="problemTypeShow = false"
    ></u-picker>
    <u-picker
      :show="industryTypeShow"
      keyName="label"
      :columns="[industryTypeList]"
      @confirm="handleConfirmIndustryType"
      @cancel="industryTypeShow = false"
    ></u-picker>
    <u-datetime-picker
      ref="datetimePicker"
      :show="dateShow"
      v-model="dateVal"
      mode="year-month"
      :maxDate="Number(new Date())"
      :minDate="Number(new Date('1980-01'))"
      closeOnClickOverlay
      @confirm="confirm"
      @cancel="dateShow = false"
      @close="dateShow = false"
    ></u-datetime-picker>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>
<script>
import { getDictItemInfo } from '@/api/system';
import { houseAdd, houseEdit, queryHouseById, isEquNoOnly } from '@/api/houseInfo';
import { houseInfoAdd, houseInfoEdit, queryHouseInfoById } from '@/api/houseInfo.js';
import uploadImg from '../components/upload-img/upload-img.vue';
import { industryTypeList } from '@/config/enumeration.js';
export default {
  filters: {
    showQuesTypeVal: (quesType, questionType) => {
      const val = (questionType.find((x) => x.value === quesType) || {}).label;
      return val;
    },
    showIndustryTypeVal: (industryType) => {
      const val = (industryTypeList.find((x) => x.value === industryType) || {}).label;
      return val;
    },
  },
  components: {
    uploadImg,
  },
  data() {
    return {
      form: {
        houseNo: '', // 编号
        industrySel: '', // 行业选择
        houseOwnerName: '', // 户主姓名
        houseNumber: '', // 门牌号
        floorNum: '', // 房屋层数
        permanentPopulation: '', // 常住人口数
        position: '', // 房屋地址
        longitude: '',
        latitude: '',
        cffs: '', // 厨房废水
        wsjws: '', // 卫生间污水
        ytxyws: '', // 阳台洗衣污水
        cdc: '', // 化粪池（沼气池）数量
        gyc: '', // 隔油池
        mfsj: '', // 毛发收集器
        ytxyws: '', // 沉淀池
        quesList: [
          {
            quesType: '',
            quesDesc: '',
            picDataList: [],
          },
        ],
      },
      rules: {
        houseNo: [
          {
            type: 'string',
            required: true,
            message: '请输入编号',
            trigger: ['blur', 'change'],
          },
        ],
        industrySel: [
          {
            type: 'number',
            required: true,
            message: '请选择行业',
            trigger: ['blur', 'change'],
          },
        ],
        houseOwnerName: [
          {
            type: 'string',
            required: true,
            message: '请输入户主姓名',
            trigger: ['blur', 'change'],
          },
        ],
        floorNum: {
          type: 'number',
          required: true,
          message: '请输入房屋层数',
          trigger: ['blur', 'change'],
        },
        permanentPopulation: {
          type: 'number',
          required: true,
          message: '请输入人数',
          trigger: ['blur', 'change'],
        },
        position: {
          type: 'string',
          required: true,
          message: '请输入地址',
          trigger: ['blur', 'change'],
        },
        cffs: {
          type: 'number',
          required: true,
          message: '请选择',
          trigger: ['blur', 'change'],
        },
        wsjws: {
          type: 'number',
          required: true,
          message: '请选择',
          trigger: ['blur', 'change'],
        },
        ytxyws: {
          type: 'number',
          required: true,
          message: '请选择',
          trigger: ['blur', 'change'],
        },
      },
      radiolist: [
        {
          label: '是',
          value: 1,
          disabled: false,
        },
        {
          label: '否',
          value: 0,
          disabled: false,
        },
      ],
      questionInit: {
        quesType: '',
        quesDesc: '',
        picDataList: [],
      },
      id: null,
      townId: null,
      quesIndex: 0,
      houseInfoPageParams: null,
      eventChannel: null,
      dateShow: false,
      dateVal: '',
      questionType: [],
      problemTypeShow: false,
      pageOverfllow: false,
      editHouseInfo: {},
      disabledNext: false,
      industryTypeShow: false,
      industryTypeList,
      tuyaIndex: 0,
    };
  },
  async onLoad(option) {
    const eventChannel = this.getOpenerEventChannel();
    this.eventChannel = eventChannel;
    eventChannel.on('houseInfo', (data) => {
      this.houseInfoPageParams = data;
      this.townId = data.townId;
      this.id = data.id; // 获取问题类型数据字典
      this.getDictListFun();
      this.getDetailData();
    });
  },
  onReady() {
    //字典 房屋问题类型 ps_house_question_type
    this.getDictListFun('ps_house_question_type');
  },
  mounted() {
    this.$refs.form1.setRules(this.rules);
    this.$refs.datetimePicker.setFormatter(this.formatter);
  },
  methods: {
    handleSetPageOverfllow(flag) {
      this.pageOverfllow = flag;
    },
    async handleCheckHouseNo(houseNo) {
      try {
        if (!houseNo) return;
        const { data } = await isEquNoOnly({ no: houseNo, townId: this.townId });
        if (!data.result) {
          this.disabledNext = true;
          uni.showToast({
            title: '编号重复，请修改！',
            icon: 'error',
          });
        } else {
          this.disabledNext = false;
        }
      } catch (e) {
        //TODO handle the exception
        this.disabledNext = false;
      }
    },
    async getDictListFun(dictCode) {
      try {
        const res = await getDictItemInfo({
          dictCode,
        });
        this.questionType = (res.data.result || []).map((x) => {
          return {
            name: x.itemText,
            label: x.itemText,
            value: x.itemValue,
          };
        });
      } catch (e) {
        //TODO handle the exception
      }
    },
    async getDetailData() {
      const id = this.id;
      if (!id) return;
      try {
        const res = await queryHouseInfoById({
          id,
        });
        const editHouseInfo = res.data.result;
        const dataPartInfo = editHouseInfo?.data || {};
        this.editHouseInfo = editHouseInfo;
        let quesListPartInfo = [
          {
            quesType: '',
            quesDesc: '',
            picDataList: [],
          },
        ];
        if (editHouseInfo?.quesList.length) {
          quesListPartInfo = editHouseInfo.quesList.map((x) => {
            x.quesType = x.quesType + '';
            x.picDataList = x.picData ? JSON.parse(x.picData) : [];
            x.picDataList = x.picDataList.map((x) => {
              return {
                url: x.picUrl,
                name: x.picName,
              };
            });
            return x;
          });
        }
        const position = dataPartInfo.longitude + ',' + dataPartInfo.latitude;
        const cffs = [0, 1].includes(dataPartInfo.cffs) ? dataPartInfo.cffs : '';
        const wsjws = [0, 1].includes(dataPartInfo.wsjws) ? dataPartInfo.wsjws : '';
        const ytxyws = [0, 1].includes(dataPartInfo.ytxyws) ? dataPartInfo.ytxyws : '';
        const gyc = [0, 1].includes(dataPartInfo.gyc) ? dataPartInfo.gyc : '';
        const mfsj = [0, 1].includes(dataPartInfo.mfsj) ? dataPartInfo.mfsj : '';
        const cdc = [0, 1].includes(dataPartInfo.cdc) ? dataPartInfo.cdc : '';
        this.form = {
          houseNo: dataPartInfo.houseNo || '', // 编号
          industrySel: +dataPartInfo.industrySel || '', // 行业选择
          houseOwnerName: dataPartInfo.houseOwnerName || '', // 户主姓名
          houseNumber: dataPartInfo.houseNumber || '', //房屋层数
          floorNum: dataPartInfo.floorNum || '', //门牌号
          permanentPopulation: dataPartInfo.permanentPopulation || '', // 常住人口数
          position: dataPartInfo.longitude ? position : '', //房屋地址
          longitude: dataPartInfo.longitude || '', // 经度
          latitude: dataPartInfo.latitude || '', // 维度
          cffs, // 厨房废水
          wsjws, // 卫生间污水
          ytxyws, // 阳台洗衣污水
          zqcsl: dataPartInfo.zqcsl, //化粪池（沼气池）数量
          gyc, // 隔油池
          mfsj, // 毛发收集器
          cdc, // 沉淀池
          quesList: [...quesListPartInfo],
        };
      } catch (e) {
        //TODO handle the exception
      }
    },
    selectAddress() {
      // 点击调起地图选择位置
      const that = this;
      uni.authorize({
        scope: 'scope.userLocation',
        success(res) {
          // 选择位置
          uni.chooseLocation({
            success: function (res) {
              that.form.position = res.longitude + ',' + res.latitude;
              that.form.longitude = res.longitude;
              that.form.latitude = res.latitude;
              that.$refs.form1.validateField('position');
            },
            fail(error) {
              // console.log('选择位置失败', error)
            },
          });
        },
      });
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    confirm(e) {
      this.dateShow = false;
      this.form.buildDate = this.result(e.value, e.mode);
      this.$refs.form1.validateField('buildDate');
    },
    result(time, mode) {
      // debu
      const timeFormat = uni.$u.timeFormat,
        toast = uni.$u.toast;
      switch (mode) {
        case 'datetime':
          return timeFormat(time, 'yyyy-mm-dd hh:MM');
        case 'date':
          return timeFormat(time, 'yyyy-mm-dd');
        case 'year-month':
          return timeFormat(time, 'yyyy年mm月');
        case 'time':
          return time;
        default:
          return '';
      }
    },
    navigateBack() {
      uni.navigateBack();
    },
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast('验证码已发送');
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast('倒计时结束后再发送');
      }
    },
    submit() {
      if (this.disabledNext) {
        uni.showToast({
          title: '编号重复，请修改！',
          icon: 'error',
        });
        return;
      }
      this.$refs.form1.validate().then(async (res) => {
        const quesList = this.form.quesList
          .filter((item) => {
            return item.quesDesc || item.quesType || item.picDataList.length;
          })
          .map((question) => {
            question.picDataList = question.picDataList.map((x) => {
              return {
                picName: x.name,
                picUrl: x.url,
              };
            });
            return question;
          });
        console.log(quesList, 'quesList');
        const buildDate = this.form.buildDate
          ? (this.form.buildDate || '').replaceAll('年', '-').replaceAll('月', '-') + '01 00:00:00'
          : '';
        const params = {
          ...this.form,
          ...this.houseInfoPageParams,
          buildDate, // buildDate格式化
          quesList,
          type: 4,
        };
        let api = null;
        if (this.id) {
          api = houseInfoEdit;
        } else {
          api = houseInfoAdd;
        }
        if (!api) {
          return;
        }
        await api(params)
          .then((res) => {
            if (res.data.code === 200) {
              uni.showToast({
                title: '已提交',
                icon: 'success',
              });
              this.eventChannel.emit('refresh');
              uni.navigateBack();
            } else {
              uni.showToast({
                title: res.data.message,
                icon: 'none',
              });
            }
          })
          .catch((e) => {
            uni.showToast({
              title: e,
              icon: 'none',
            });
          });
      });
    },
    hideKeyboard() {
      uni.hideKeyboard();
    },
    handleConfirmQues(res) {
      this.form.quesList[this.quesIndex].quesType = res.value[0].value;
      this.problemTypeShow = false;
    },
    handleConfirmIndustryType(res) {
      this.form.industrySel = res.value[0].value;
      this.industryTypeShow = false;
      this.$nextTick(() => {
        this.$refs.form1.validateField('industrySel');
      });
    },
    addQuestion() {
      this.form.quesList.push({
        ...this.questionInit,
      });
    },
    deleteQuestion(i) {
      const quesList = this.form.quesList;
      if (quesList.length === 1) {
        this.form.quesList = [
          {
            quesType: null,
            quesDesc: null,
            picDataList: [],
          },
        ];
      } else {
        this.form.quesList.splice(i, 1);
      }
    },
    handleTuYa(i) {
      this.tuyaIndex = i;
      uni.navigateTo({
        url: '/subpak_survey/tuya/tuya',
        events: {
          resetQues: (editedPic) => {
            console.log(editedPic);
            this.form.quesList[this.tuyaIndex].picDataList = [editedPic];
          },
        },
        success: (res) => {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('showTuya', this.form.quesList[i]);
        },
      });
    },
    handleViewPic(picPath) {
      console.log('handleViewPic', picPath);
      // 预览图片
      uni.previewImage({
        urls: [picPath],
      });
    },
    handleClearImg(i, j) {
      this.form.quesList[i].picDataList.splice(j, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  position: relative;
  background-color: #fff;
  padding: 0 30rpx 180rpx;
}

.pagenoscroll {
  box-sizing: border-box;
  height: 100vh;
  overflow: hidden;
}

.scroll-Y {
  box-sizing: border-box;
  padding: 0 30rpx 180rpx;
  height: 100%;
  width: 100%;
}

.line {
  width: 100%;
  height: 4rpx;
  background: linear-gradient(90deg, #26ffea00 0%, #1e4d79 50%, #26ffea00 100%);
}

.page-btn-wrap {
  position: fixed;
  display: flex;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 166rpx;
  box-shadow: 0 -4rpx 24rpx 0 #00000014;
  background: white;
  z-index: 99;
}

.question-container {
  border: 1rpx solid #cccccc;
  border-radius: 4rpx;
  padding: 0 24rpx;
  margin-bottom: 24rpx;
}

.files-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32rpx 24rpx;
}

.btn-item {
  padding: 16rpx 32rpx 0 32rpx;
  width: 100%;
  height: 100%;
}

.pic-wrap {
  width: 100%;
  height: 100%;
}

.pic-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pic-close-btn {
  position: absolute;
  top: 24rpx;
  right: 24rpx;
}
</style>
